package leetcode.code0451;

import java.util.Arrays;

import leetcode.IDebug;

public class Solution implements IDebug {

	public String frequencySort(String s) {
		char[] cs = s.toCharArray();
		int[][] cnts = new int[128][2];
		for (int i = 0; i < cnts.length; i++) {
			cnts[i][1] = i;
		}
		for (int i = 0; i < cs.length; i++) {
			cnts[cs[i]][0]++;
		}
		Arrays.sort(cnts, (a, b) -> b[0] - a[0]);
		StringBuffer sb = new StringBuffer();
		int p = 0;
		while (cnts[p][0] != 0) {
			int[] cur = cnts[p];
			int size = cur[0];
			char c = (char) cur[1];
			sb.append(this.append(c, size));
			p++;
		}
		return sb.toString();
	}

	private StringBuffer append(char c, int size) {
		StringBuffer sb = new StringBuffer();
		if (size == 0) {
			return sb;
		}
		if (size == 1) {
			return sb.append(c);
		}
		StringBuffer half = this.append(c, size >> 1);
		if ((size & 1) == 0) {
			return sb.append(half).append(half);
		}
		return sb.append(half).append(half).append(c);
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
